package com.example.demo.controller;

import com.example.demo.common.ResultAjax;
import com.example.demo.common.SessionUtil;
import com.example.demo.model.ArticleInfo;
import com.example.demo.model.UserInfo;
import com.example.demo.model.vo.UserInfoVo;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@RestController
@RequestMapping("/article")
public class ArticleController {
    private static final int DESC_LENGTH = 120;
    private static final int PAGE_SIZE = 4;
    @Resource
    private ArticleService articleService;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    @Resource
    private UserService userService;

    /**
     * 展示用户文章
     * @param request
     * @return
     */
    @RequestMapping("/list")
    // 通过session获取登录的用户信息，不要在去查询
    public ResultAjax myArticles(HttpServletRequest request) {
        // 判断用户是否登录
        UserInfo userInfo = SessionUtil.getUser(request);
        if (userInfo == null) {
            // 用户未登录，只有登录才能执行操作
            return ResultAjax.fail(-1,"请先登录");
        }
        System.out.println(userInfo.getId());
        // 此时已经登录，将文章信息返回给登录的用户
        List<ArticleInfo>articleList = articleService.getArticlesByUid(userInfo.getId());
        // 无简介功能，这里需要处理展示的文字
        if (articleList != null && articleList.size() > 0) {
            // 多线程并发处理list中的数据
            articleList.stream().parallel().forEach((article)->{
                if (article.getContent().length() > DESC_LENGTH) {
                    // 如果超过了指定的长度，截取指定长度
                    article.setContent(article.getContent().substring(0,DESC_LENGTH));
                }
            });
        }
        return ResultAjax.success(articleList);
    }

    /**
     * 添加文章
     * @param articleInfo
     * @param request
     * @return
     */
    @RequestMapping("/insert")
    public ResultAjax insert(ArticleInfo articleInfo, HttpServletRequest request) {
        // 校验参数
        if (articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle()) ||
                !StringUtils.hasLength(articleInfo.getContent())) {
            return ResultAjax.fail(-1,"非法参数");
        }
        // 归属判断
        UserInfo userInfo = SessionUtil.getUser(request);
        if (userInfo == null) {
            return ResultAjax.fail(-2,"请先登录！");
        }
        articleInfo.setUid(userInfo.getId());
        // 将文章信息添加到数据库
        int result = articleService.insert(articleInfo);
        return ResultAjax.success(result);
    }

    @RequestMapping("/update_init")
    public ResultAjax updateInit(Integer aid, HttpServletRequest request) {
        // 校验参数
        if (aid == null || aid <= 0) {
            return ResultAjax.fail(-1,"非法参数");
        }
        // 归属判断
        UserInfo userInfo = SessionUtil.getUser(request);
        if (userInfo == null) {
            return ResultAjax.fail(-2,"请先登录");
        }
        // 返回当前文章
        ArticleInfo article = articleService.getArticleByAidAndUid(aid,userInfo.getId());
        return ResultAjax.success(article);
    }

    /**
     * 修改文章
     * @param articleInfo
     * @param request
     * @return
     */
    @RequestMapping("/update")
    public ResultAjax update(ArticleInfo articleInfo, HttpServletRequest request) {
        // 校验参数
        if (articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle()) ||
                !StringUtils.hasLength(articleInfo.getContent()) ||
                 articleInfo.getId() <= 0) {
            return ResultAjax.fail(-1,"非法参数");
        }
        // 获取登录对象
        UserInfo userInfo = SessionUtil.getUser(request);
        if (userInfo == null) {
            return ResultAjax.fail(-2,"请先登录！");
        }
        // 对文章进行修改，此处不需要组装uid
        int result = articleService.update(articleInfo);
        return ResultAjax.success(result);
    }

    /**
     * 展示文章详情
     * @param aid
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @RequestMapping("/detail")
    public ResultAjax detail(Integer aid) throws ExecutionException, InterruptedException {
        // 参数校验
        if (aid == null || aid <= 0) {
            return ResultAjax.fail(-1,"非法参数！");
        }
        // 查询文章详情
        ArticleInfo articleInfo = articleService.detail(aid);
        if (articleInfo == null || articleInfo.getId() <= 0) {
            return ResultAjax.fail(-1,"非法参数！");
        }
        // 通过uid查询用户信息 多线程
        FutureTask<UserInfoVo> userTask = new FutureTask<>(()->{
           return userService.getUserByUid(articleInfo.getUid());
        });
        taskExecutor.submit(userTask);
        // 查询用户文章数量
        FutureTask<Integer> articleCountTask = new FutureTask<>(()->{
            return articleService.getArticlesCount(articleInfo.getUid());
        });
        taskExecutor.submit(articleCountTask);
        // 组装数据
        UserInfoVo userInfoVo = userTask.get();
        int count = articleCountTask.get();
        userInfoVo.setCount(count);
        HashMap<String,Object> result = new HashMap<>();
        result.put("user",userInfoVo);
        result.put("article",articleInfo);
        return ResultAjax.success(result);
    }

    @RequestMapping("/read_count")
    public ResultAjax readCount(Integer aid) {
        // 参数校验
        if (aid == null || aid <= 0) {
            return ResultAjax.fail(-1,"参数有误");
        }
        // 实现阅读量增加
        int result = articleService.increaseReadCount(aid);
        return ResultAjax.success(result);
    }

    @RequestMapping("/get_page")
    public ResultAjax getPage(Integer index, Integer size) throws ExecutionException, InterruptedException {
        // 参数校正
        if (index == null || index <= 0) {
            index = 1;
        }
        if (size == null || size <= 0) {
            size = PAGE_SIZE;
        }
        // 分页查询，显示页面 多线程
        Integer finalPageSize = size; // 变量捕获
        Integer pageOffset = size*(index - 1);
        FutureTask<List<ArticleInfo>> listTask = new FutureTask<>(()->{
            return articleService.getArticlesByPage(finalPageSize, pageOffset);
        });
        // 获取文章总页数
        FutureTask<Integer> articleCount = new FutureTask<>(()->{
            int artCount = articleService.AllArticlesCount();
            double total = (artCount*1.0) / (finalPageSize*1.0);
            return (int) Math.ceil(total);
        });
        taskExecutor.submit(listTask);
        taskExecutor.submit(articleCount);
        // 组装数据
        HashMap<String,Object> articles = new HashMap<>();
        List<ArticleInfo> list = listTask.get();
        int total = articleCount.get();
        articles.put("articles",list);
        articles.put("total",total);
        return ResultAjax.success(articles);
    }
}
